package helper

import (
	"fmt"

	"github.com/buger/jsonparser"
)

type H map[string]interface{}

const (
	HttpCodeOK           = 0
	HttpCodeAuthFail     = 10001
	HttpCodeTimeout      = 10002
	HttpCodeValidateFail = 10003
	HttpCodeInternalFail = 10004
)

func HttpRespErrorMarshal(code int, msg string) []byte {
	//不采用json.Marshal,其耗时为29.758µs, 采用Sprintf的耗时为1.147µs
	return []byte(fmt.Sprintf(`{"code": %d, "msg": "%s", "data": {}}`, code, msg))
}

func HttpRespDataMarshal(data string) []byte {
	return []byte(fmt.Sprintf(`{"code": %d, "msg": "success", "data": %s}`, HttpCodeOK, data))
}

func HttpRespCode(body []byte) (int64, error) {
	return jsonparser.GetInt(body, "code")
}
func HttpRespMsg(body []byte) (string, error) {
	return jsonparser.GetString(body, "msg")
}
func HttpRespData(body []byte) (string, error) {
	return jsonparser.GetString(body, "data")
}
func HttpRespDataRaw(body []byte) ([]byte, error) {
	data, valType, _, err := jsonparser.Get(body, "data")
	if valType != jsonparser.Object {
		return []byte{}, fmt.Errorf("type is invalid: %s", valType.String())
	}
	return data, err
}

// func IsReachable(addr string) bool {
// 	if addr[len(addr)-1:] != "/" {
// 		addr += "/"
// 	}
// 	addr += "ping"
// 	ret, err := Command("curl -sS '" + addr + "' || exit 1")
// 	fmt.Println("addr", addr, "ret", string(ret), "err", err)
// 	return err == nil && string(ret) == `"pong!"`
// }
